import React, { useMemo, useState, useEffect } from 'react';
import { cline, Ret, Title, useHigh, GridTable, useCmd, WaitUmd, MainView, loc_str, urlTb, show_mt, filter_row, FindBarBase, is_empty, loc } from 'sui';
import { get_init, cell_row } from 'trace/cmd';
import { utc_offset } from 'cache';

const HisView = ({ mod, title, hreturn, col }) => {
    const [opt_find, optFind] = useState();
    const [main, setMain] = useState([]);
    const [high] = useHigh(200, 100);
    const umd = useCmd();

    useEffect(() => get_init(optFind), []);

    const filteredRows = useMemo(() => {
        if (is_empty(main) || is_empty(col)) {
            return null;
        }

        const lst = col.map(d => d.sn);

        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter, col]);

    const hfind = (value) => {
        const herr = (e) => {
            alert(`${loc("l_307")}: ${e}`);
        };

        if (!value["time"]) {
            herr(loc("l_308"));
            return;
        }

        const utc = utc_offset();

        const opt = [
            {ge: "time", v: loc_str(value["t_start"]), utc: utc},
            {le: "time", v: loc_str(value["t_end"]), utc: utc},
            {eq: "line", v: cline()},
        ];

        const tab = `his${mod}`;

        const cmd = {
            n: tab,
            obj: "*",
            opt: {
                desc: true,
                and: opt,
            }
        };

        umd.startWait();

        urlTb(null, "get", cmd,
            r => {
                const data = r[tab]["data"];
                let row = cell_row(data);
                setMain(row);
                umd.endWait();
            },
            e => {
                setMain(null);
                umd.endWait();
            });
    };

    const Right = () => (
        <div className="inline-flex">
            <Ret hcmd={hreturn}/>
        </div>
    );

    const Left = () => <Title mod={loc("l_884")} sub={title}/>;

    const hclear = () => get_init(optFind);

    const ctl = {
        ctl: [
            {sn: "time", name: loc("l_308"), ctl: "IkFindDate", start: "t_start", end: "t_end"},
        ]
    };

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70, frozen: true},
            {name: loc("l_101"), key: 'time', width: 180, frozen: true},
        ];

        col.forEach(d => show_mt(tmp, d, 150));

        return tmp;
    };

    return (
        <MainView>
            <FindBarBase left={<Left/>} hcmd={hfind} data={ctl} hclear={hclear} cur={opt_find} right={<Right/>} hfilter={umd.setFilter}/>
            <GridTable col={getCol()} row={filteredRows} high={high}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {HisView};
